<?php

namespace app\api\controller;

use app\admin\model\exchange\Library;
use app\admin\model\exchange\Log;
use app\admin\model\order\AppManage;
use app\admin\model\order\OrderBill;
use app\admin\model\share\ShareUser;
use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\PrepaidLogs;
use app\common\model\ShareConfig;
use app\common\model\User;
use app\common\model\User as FUser;
use think\Db;
use \app\admin\model\write\Order as WriteOrder;
use addons\shopro\model\Order as shoproOrder;
use \app\common\model\FttuserToken;
use \app\admin\model\share\CommonShare;
use addons\shopro\model\UserAddress;
use addons\shopro\model\OrderItem;
use think\exception\PDOException;


/**
 * 示例接口
 */
class Order extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['order_list', 'order_update', 'payment_method', 'reOrderSum', 'tongji_order'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // 快递鸟配置信息
    private $EbusinessID = '1781308';
    private $ApiKey = 'e77b8db4-c696-4ffa-aedc-439905644649';
//    private $ReqURL = 'https://sandboxapi.kdniao.com:8080/kdniaosandbox/gateway/exterfaceInvoke.json';
    private $ReqURL = 'https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new WriteOrder;
        $this->orderModel = new \app\admin\model\shopro\order\Order;
        $this->storeModel = new \app\admin\model\shopro\store\Store;
        // $token = $this->request->header('token');
        // if (empty($token)) {
        //     $this->error("token不能为空");
        // }
        // $user_token = (new FttuserToken())->where(['token'=>$token])->find();
        // if (empty($user_token)) {
        //     $this->error("请先登录");
        // } else {
        //     $this->user_id = $user_token['user_id'];
        // }
        $this->user_id = $this->auth->id;
    }

    /**
     * 核销接口，验证订单是否有效
     */
    // public function writeoff()
    // {
    //     $order_no =  $this->request->post("order_no"); // ID
    //     $verify_name = $this->request->post("verify_name");
    //     $verify_order = $this->request->post("verify_order");
    //     $row = $this->model->get(['order_no'=>$order_no]);
    //     if (empty($row)) {
    //         $this->error("订单不存在");
    //     }
    //     if ($row['is_verify'] == 1) {
    //         $this->error("订单已核销");
    //     }

    //     $item_id =  $this->request->post("item_id"); // 商品ID
    //     $real_name =  $this->request->post("real_name"); // 收货人姓名
    //     $user_phone =  $this->request->post("user_phone"); // 收货人手机号
    //     $province =  $this->request->post("province"); // 省
    //     $city =  $this->request->post("city"); // 市
    //     $district =  $this->request->post("district"); // 区
    //     $address_detail =  $this->request->post("address_detail"); // 详细地址
    //     $goods_detail =  $this->request->post("goods_detail"); // 商品详情
    //     $pic_url =  $this->request->post("pic_url"); // 商品图片
    //     $pic_url_json =  $this->request->post("pic_url_json"); // 轮播图
    //     $body =  $this->request->post("body"); // 商品内容
    //     $goods_type =  $this->request->post("goods_type"); // 商品类型
    //     $total_price =  $this->request->post("total_price"); // 订单总价
    //     $app_id =  $this->request->post("app_id");
    //     if (empty($app_id)) {
    //         $app_id = "write";
    //     }

    //     // 添加订单
    //     $data = array(
    //         'created_at' =>  date("Y-m-d H:i:s"),
    //         'uid' => $this->user_id,
    //         'item_id' => $item_id,
    //         'out_trade_no' => $this->english_num(),
    //         'real_name' => $real_name,
    //         'user_phone' => $user_phone,
    //         'province' => $province,
    //         'city' => $city,
    //         'district' => $district,
    //         'address_detail' => $address_detail,
    //         'goods_detail' => $goods_detail,
    //         'pic_url' => $pic_url,
    //         'pic_url_json' => $pic_url_json,
    //         'body' => $body,
    //         'goods_type' => $goods_type,
    //         'total_price' => $total_price,
    //         'handling_method' => 1, // 办理方式 0-分期 1-不分期 2-赠送
    //         'pay_time' => date("Y-m-d H:i:s"), //支付方式
    //         'pay_type' => 'coupons_app',//支付方式
    //         'pay_price' => $row['money'],
    //         'pay_status' => 1, //支付状态
    //         'status' => 1,//订单状态
    //         'app_id' => $app_id,
    //         'card_sn' =>'-',
    //         'deduction_amount' =>'0.00'
    //     );
    //     $order_id = Db::connect('database_b')->table('orders')->insertGetId($data);

    //     $result =$this->model->where(['order_no' =>$order_no])->update(['is_verify'=>1, 'verify_name'=>$verify_name,'verify_order'=>$verify_order]);

    //     if ($result) {
    //         $this->success('成功', $result);
    //     } else {
    //         $this->error("失败");
    //     }
    //     $this->success('返回成功', ['action' => 'test1']);
    // }

    private function english_num()
    {
        $s = '0123456789';
        $temp = '';
        while (strlen($temp) < 32) {
            $index = mt_rand(0, strlen($s) - 1);
            $temp .= $s[$index];
        }
        return $temp;
    }

    /**
     * 核销接口，验证提货劵是否有效
     */
    public function writeoff()
    {
        $order_no = $this->request->post("order_no"); // ID
        $status = $this->request->post("status");
        $verify_name = $this->request->post("verify_name");
        $verify_order = $this->request->post("verify_order");
        $row = $this->model->get(['order_no' => $order_no, 'status' => $status]);
        if (empty($row)) {
            $this->error("订单不存在");
        }
        if ($row['is_verify'] == 1) {
            $this->error("订单已核销");
        }

        $address_id = $this->request->post("address_id"); // ID
        $address = UserAddress::info(['id' => $address_id]);
        if (empty($address)) {
            $this->error("地址不能为空");
        }
        $real_name = $address["consignee"];//$this->request->post("real_name"); // 收货人姓名
        $user_phone = $address["phone"];//$this->request->post("user_phone"); // 收货人手机号
        $province_name = $address["province_name"];//$this->request->post("province_name"); // 省
        $city_name = $address["city_name"];//$this->request->post("city_name"); // 市
        $area_name = $address["area_name"];//$this->request->post("area_name"); // 区
        $province_id = $address["province_id"];//$this->request->post("province_id"); // 省
        $city_id = $address["city_id"];//$this->request->post("city_id"); // 市
        $area_id = $address["area_id"];//$this->request->post("area_id"); // 区
        $address_detail = $address["address"];//$this->request->post("address_detail"); // 详细地址
        $total_price = $this->request->post("total_price"); // 订单总价
        $goods_id = $this->request->post("goods_id"); // 商品id
        // 添加订单
        $data = array(
            'type' => 'goods',
            'order_sn' => $this->english_num(),
            'user_id' => $this->user_id,
            'goods_amount' => $total_price,
            'dispatch_amount' => 0,
            'phone' => $user_phone,
            'consignee' => $real_name,
            'province_name' => $province_name,
            'city_name' => $city_name,
            'area_name' => $area_name,
            'address' => $address_detail,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'area_id' => $area_id,
            'status' => 1,
            'total_amount' => $total_price,
            'total_fee' => $total_price,
            'goods_id' => $goods_id,
            'discount_fee' => 0,
            'coupon_fee' => 0,
            'pay_fee' => $total_price,
            'goods_original_amount' => $total_price,
            'pay_type' => 'wallet',
            'paytime' => time(),
            'platform' => 'Coupon',
            'createtime' => time(),
        );
        $order = new shoproOrder();
        $order->allowField(true)->save($data);
        $detail = \addons\shopro\model\Goods::getGoodsDetail($goods_id);
        $orderItem = new OrderItem();
        $orderItem->user_id = $this->user_id;
        $orderItem->order_id = $order->id;
        $orderItem->goods_id = $goods_id;
        $orderItem->goods_type = 'normal';
        $orderItem->goods_sku_price_id = 0;// 规格id
        $orderItem->activity_id = 0;     // 商品当前的活动类型
        $orderItem->activity_type = null;     // 商品当前的活动类型
        // 当前商品规格对应的 活动下对应商品规格的 id
        $orderItem->item_goods_sku_price_id = 0;
        $orderItem->goods_title = $detail['title'];
        $orderItem->goods_image = $detail['image'];
        $orderItem->goods_original_price = $detail['original_price'];
        $orderItem->pay_price = $total_price;        // 平均计算单件商品不算运费，算折扣时候的金额
        $orderItem->goods_price = $total_price;
        $orderItem->goods_num = 1;
        $orderItem->goods_weight = 0;
        $orderItem->dispatch_status = 0;
        $orderItem->dispatch_fee = 0;
        $orderItem->dispatch_type = 'express';
        $orderItem->dispatch_id = 0;
        $orderItem->store_id = 0;
        $orderItem->aftersale_status = 0;
        $orderItem->comment_status = 0;
        $orderItem->refund_status = 0;
        $ext = [];
        $orderItem->ext = json_encode($ext);
        $orderItem->save();
        $result = $this->model->where(['order_no' => $order_no])->update(['is_verify' => 1, 'verify_name' => $verify_name, 'verify_order' => $verify_order]);
        (new CommonShare())->add_share_order($order->id, $goods_id, $this->user_id);
        if ($result) {
            $this->success('成功', $result);
        } else {
            $this->error("失败");
        }
        $this->success('返回成功', ['action' => 'test1']);
    }

    /**
     * 积分和现金购买商品
     */
    public function order_add()
    {
        $u = FUser::get($this->auth->id);

        /*$m_day = strtotime(date('Y-m',time()));
        $r_where['user_id'] = $u->id;
        $r_where['createtime'] = $m_day;
        $r_where['one_day'] = 1;
        $r_data = Db::name("shopro_order")->where($r_where)->find();
        if($r_data){
            $this->error("没月一品一次，每月只能买一次");
        }*/
        $pay_type = $this->request->post("pay_type"); //

        $address_id = $this->request->post("address_id"); // ID
        $address = UserAddress::info(['id' => $address_id]);
        if (empty($address)) {
            $this->error("地址不能为空");
        }
        Db::startTrans();
        $real_name = $address["consignee"];//$this->request->post("real_name"); // 收货人姓名
        $user_phone = $address["phone"];//$this->request->post("user_phone"); // 收货人手机号
        $province_name = $address["province_name"];//$this->request->post("province_name"); // 省
        $city_name = $address["city_name"];//$this->request->post("city_name"); // 市
        $area_name = $address["area_name"];//$this->request->post("area_name"); // 区
        $province_id = $address["province_id"];//$this->request->post("province_id"); // 省
        $city_id = $address["city_id"];//$this->request->post("city_id"); // 市
        $area_id = $address["area_id"];//$this->request->post("area_id"); // 区
        $address_detail = $address["address"];//$this->request->post("address_detail"); // 详细地址
        $total_price = $this->request->post("total_price"); // 订单总价
        $goods_id = $this->request->post("goods_id"); // 商品id
        $good_data = Db::name("shopro_goods")->where(['id' => $goods_id])->find();
        $s_data = Db::name("share_user")->where(['user_id' => $u->id])->find();
        if ($pay_type == 'wallet') {
            if (($s_data['price'] + $s_data['mutual_money']) < $total_price) {
                $this->error("金额不足");
            }
            $p_stat = false;
            $in_data['user_id'] = $u->id;
            $in_data['money'] = $total_price;
            if ($s_data['mutual_money'] < $total_price) {
                $score = $s_data['price'] - ($total_price - $s_data['mutual_money']);
                $p_stat = Db::name("share_user")->where(['user_id' => $u->id])->update(['price' => $score, 'mutual_money' => 0]);
                $in_data['before'] = $s_data['price'];
                $in_data['after'] = $score;
                $in_data['memo'] = "购买商品(其中互助金使用金额：" + $total_price + ")";
            } else {
                $p_stat = Db::name("share_user")->where(['user_id' => $u->id])->update(['mutual_money' => ($s_data['mutual_money'] - $total_price)]);
                $in_data['before'] = $s_data['price'];
                $in_data['after'] = $s_data['price'];
                $in_data['memo'] = "购买商品(其中互助金使用金额：" + $total_price + ")";
            }
            if (!$p_stat) {
                Db::rollback();
                $this->error("金额修改失败");
            }
            $in_data['createtime'] = time();
            $in_stat = Db::name("user_money_log")->insert($in_data);
            if (!$in_stat) {
                Db::rollback();
                $this->error("金额修改失败");
            }
        } elseif ($pay_type == 'score') {
            if ($s_data['score'] < $total_price) {
                $this->error("积分不足");
            }
            $score = $s_data['score'] - $total_price;
            $p_stat = Db::name("share_user")->where(['user_id' => $u->id])->update(['score' => $score]);
            if (!$p_stat) {
                Db::rollback();
                $this->error("积分修改失败");
            }
            $in_data['user_id'] = $total_price;
            $in_data['score'] = $total_price;
            $in_data['before'] = $s_data['score'];
            $in_data['after'] = $score;
            $in_data['memo'] = "购买商品";
            $in_data['createtime'] = time();
            $in_data['goods_id'] = $goods_id;
            $in_stat = Db::name("user_score_log")->insert($in_data);
            if (!$in_stat) {
                Db::rollback();
                $this->error("积分修改失败");
            }
            // \addons\shopro\model\User::score($total_price, $u->id, '', 0, "购买商品");
        } else {
            $this->error("支付方式错误");
        }
        // 添加订单
        $data = array(
            'type' => 'goods',
            'order_sn' => $this->english_num(),
            'user_id' => $this->user_id,
            'goods_amount' => $good_data['price'],
            'dispatch_amount' => 0,
            'phone' => $user_phone,
            'consignee' => $real_name,
            'province_name' => $province_name,
            'city_name' => $city_name,
            'area_name' => $area_name,
            'address' => $address_detail,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'area_id' => $area_id,
            'status' => 1,
            'total_amount' => $total_price,
            'total_fee' => $total_price,
            'goods_id' => $goods_id,
            'discount_fee' => 0,
            'coupon_fee' => 0,
            'pay_fee' => $total_price,
            'goods_original_amount' => $good_data['price'],
            'pay_type' => $pay_type,
            'paytime' => time(),
            'platform' => 'Coupon',
            'createtime' => time(),
            'one_day' => 1,
        );
        $order = new \addons\shopro\model\Order();
        $order->allowField(true)->save($data);
        $detail = \addons\shopro\model\Goods::getGoodsDetail($goods_id);
        $orderItem = new OrderItem();
        $orderItem->user_id = $this->user_id;
        $orderItem->order_id = $order->id;
        $orderItem->goods_id = $goods_id;
        $orderItem->goods_type = 'normal';
        $orderItem->goods_sku_price_id = 0;// 规格id
        $orderItem->activity_id = 0;     // 商品当前的活动类型
        $orderItem->activity_type = null;     // 商品当前的活动类型
        // 当前商品规格对应的 活动下对应商品规格的 id
        $orderItem->item_goods_sku_price_id = 0;
        $orderItem->goods_title = $detail['title'];
        $orderItem->goods_image = $detail['image'];
        $orderItem->goods_original_price = $detail['original_price'];
        $orderItem->pay_price = $total_price;        // 平均计算单件商品不算运费，算折扣时候的金额
        $orderItem->goods_price = $total_price;
        $orderItem->goods_num = 1;
        $orderItem->goods_weight = 0;
        $orderItem->dispatch_status = 0;
        $orderItem->dispatch_fee = 0;
        $orderItem->dispatch_type = 'express';
        $orderItem->dispatch_id = 0;
        $orderItem->store_id = 0;
        $orderItem->aftersale_status = 0;
        $orderItem->comment_status = 0;
        $orderItem->refund_status = 0;
        $ext = [];
        $orderItem->ext = json_encode($ext);
        $orderItem->save();

        (new CommonShare())->add_share_order($order->id, $goods_id, $this->user_id);
        if ($orderItem) {
            Db::commit();
            $this->success('成功');

        } else {
            Db::rollback();
            $this->error("失败");

        }
        $this->success('返回成功', ['action' => 'test1']);
    }

    public function order_transfer()
    {
        $mobile = $this->request->post("mobile"); // 手机号
        $address = $this->request->post("address"); //
        $id = $this->request->post("order_id"); // ID
        $captcha = $this->request->post("captcha");//短信验证码
        if (!$captcha) {
            $this->error(__('验证码不能为空'));
        }
        $arr_temp = array(13131388888,
            18213345601, 18213345602, 18213345603, 18213345604, 18213345605, 18213345606, 18213345607, 18213345608, 18213345609, 18213345610, 18213345611, 18213345612, 18213345613, 18213345614, 18213345615, 18213345616, 18213345617, 18213345619, 18213345620, 18213345621, 18213345622, 18213345623, 18213345624, 18213345625, 18213345626, 18213345627, 18213345628, 13136281919
        );
        $is_true = true;
        if (in_array($this->auth->mobile, $arr_temp)) {
            if ($this->auth->mobile == '13131388888' && $captcha == '131313') {
                $is_true = false;
            }
            if ($this->auth->mobile != '13131388888' && $captcha == '1111') {
                $is_true = false;
            }
        }
        if ($is_true) {
            if (!Sms::check($this->auth->mobile, $captcha, 'transferpoints')) {
                $this->error(__('验证码不正确'));
            }
        }
        $fttuser = User::getByMobile($mobile);
        if (empty($fttuser)) {
            $this->error('手机号不存在');
        }
        if ($this->auth->mobile == $mobile) {
            $this->error('自己不能转赠给自己');
        }
        $order = Db::name("shopro_order")->where(['id' => $id])->find();
        if (!$order) {
            $this->error("订单不存在");
        }
        if ($order['user_id'] != $this->user_id) {
            $this->error("不是本用户的订单");
        }
        if ($order['status'] == 0) {
            $this->error("订单状态不对");
        }

        $data = array(
            'user_id' => $fttuser['id'],
            'phone' => $mobile,
            'address' => $address,
        );

        $save_data = Db::name("shopro_order")->where(['id' => $id])->update($data);
        if ($save_data) {
            $this->success('转户成功');
        }
        $this->error('转户失败');
    }

    /**
     * @return void
     */
    public function payment_method()
    {

        // 判断当前时间是否在21点和次日9点之间
        $time = time();
        $begin_start_time = strtotime(date('Y-m-d 21:00:00'));
        $end_time = strtotime(date('Y-m-d 09:00:00', strtotime('+1 day')));

        if (date('H', $time) < 9) {
            $this->success('返回成功', ['status' => true]);
        } else {
            if ($time > $begin_start_time && $time < $end_time) {
                // 说明在21点到次日9点之间
                $this->success('返回成功', ['status' => true]);
            }
        }
        $this->success('返回成功', ['status' => false]);
    }

    /**
     * 易付卷下单(废弃)
     * @return void
     * @throws \think\exception\DbException
     */
    public function prepaid()
    {
        $address_id = $this->request->post("address_id"); // ID
        $address = UserAddress::info(['id' => $address_id]);
        if (empty($address)) {
            $this->error("地址不能为空");
        }
        $goods_id = $this->request->post("goods_id"); // 商品id
        $goods = \addons\shopro\model\Goods::getGoodsDetail($goods_id);

        $real_name = $address["consignee"];//$this->request->post("real_name"); // 收货人姓名
        $user_phone = $address["phone"];//$this->request->post("user_phone"); // 收货人手机号
        $province_name = $address["province_name"];//$this->request->post("province_name"); // 省
        $city_name = $address["city_name"];//$this->request->post("city_name"); // 市
        $area_name = $address["area_name"];//$this->request->post("area_name"); // 区
        $province_id = $address["province_id"];//$this->request->post("province_id"); // 省
        $city_id = $address["city_id"];//$this->request->post("city_id"); // 市
        $area_id = $address["area_id"];//$this->request->post("area_id"); // 区
        $address_detail = $address["address"];//$this->request->post("address_detail"); // 详细地址

        // 添加订单
        $data = array(
            'type' => 'goods',
            'order_sn' => $this->english_num(),
            'user_id' => $this->user_id,
            'goods_amount' => $goods['price'],
            'dispatch_amount' => 0,
            'phone' => $user_phone,
            'consignee' => $real_name,
            'province_name' => $province_name,
            'city_name' => $city_name,
            'area_name' => $area_name,
            'address' => $address_detail,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'area_id' => $area_id,
            'status' => 0,
            'total_amount' => $goods['price'],
            'total_fee' => $goods['price'],
            'goods_id' => $goods_id,
            'discount_fee' => 0,
            'coupon_fee' => 0,
            'pay_fee' => $goods['price'],
            'goods_original_amount' => $goods['price'],
            'pay_type' => 'prepaid',
            'paytime' => time(),
            'platform' => 'prepaid',
            'createtime' => time(),
        );
        $order = new \addons\shopro\model\Order();
        $order->allowField(true)->save($data);

        $orderItem = new OrderItem();
        $orderItem->user_id = $this->user_id;
        $orderItem->order_id = $order->id;
        $orderItem->goods_id = $goods_id;
        $orderItem->goods_type = 'normal';
        $orderItem->goods_sku_price_id = 0;// 规格id
        $orderItem->activity_id = 0;     // 商品当前的活动类型
        $orderItem->activity_type = null;     // 商品当前的活动类型
        // 当前商品规格对应的 活动下对应商品规格的 id
        $orderItem->item_goods_sku_price_id = 0;
        $orderItem->goods_title = $goods['title'];
        $orderItem->goods_image = $goods['image'];
        $orderItem->goods_original_price = $goods['original_price'];
        $orderItem->pay_price = $goods['price'];        // 平均计算单件商品不算运费，算折扣时候的金额
        $orderItem->goods_price = $goods['price'];
        $orderItem->goods_num = 1;
        $orderItem->goods_weight = 0;
        $orderItem->dispatch_status = 0;
        $orderItem->dispatch_fee = 0;
        $orderItem->dispatch_type = 'express';
        $orderItem->dispatch_id = 0;
        $orderItem->store_id = 0;
        $orderItem->aftersale_status = 0;
        $orderItem->comment_status = 0;
        $orderItem->refund_status = 0;
        $ext = [];
        $orderItem->ext = json_encode($ext);
        $orderItem->save();
        // 订单创建完毕，生成记录表
        $user = User::get($this->user_id);
        $orderLog = new PrepaidLogs();
        $orderLog->user_id = $this->user_id;
        $orderLog->order_id = $order->id;
        $orderLog->mobile = $user->mobile;
        $orderLog->status = 0;
        $orderLog->save();

        // 订单创建完毕，更新用户身份
        $shareConfig = ShareConfig::whereIn('goods_id', [$goods['id']])->select();

        if (!empty($shareConfig)) {
            $user = (new ShareUser())->get(['user_id' => $this->user_id]); // 分销用户
            if (!empty($user) && $user['role'] == 0) {
                $user->role = 1;
                $user->save();
            }
        }

        $this->success('返回成功', ['status' => 'true']);
    }

    public function reOrderSum()
    {
        $goods = Db::name("shopro_order")->group("goods_id")->select();
        $re_data = [];
        foreach ($goods as $k => $v) {
            if (!$v['goods_id']) continue;
            $saleNum = Db::name("shopro_order")->where('status', 'in', '1,2')->where(["goods_id" => $v['goods_id']])->count();
            $t_d = strtotime(date('Y-m-d', time()));
            $todaySaleNum = Db::name("shopro_order")->where('status', 'in', '1,2')->where(["goods_id" => $v['goods_id']])->where('createtime', '>', $t_d)->count();
            $yest_time = date("Y-m-d", strtotime("-1 day"));
            $end_time = date('Y-m-d 00:00:00');
            $yesterdaySaleNum = Db::name("shopro_order")->where('status', 'in', '1,2')->where(["goods_id" => $v['goods_id']])->where('createtime', 'between time', [$yest_time, $end_time])->count();
            $re_data[] = [
                "goodsId" => $v['goods_id'],
                "yesterdaySaleNum" => $yesterdaySaleNum,
                "todaySaleNum" => $todaySaleNum,
                "saleNum" => $saleNum
            ];
        }
        $this->success('返回成功', $re_data);
    }

    /**
     * 未到货反馈
     */
    public function order_service()
    {
        $user_id = $this->user_id;

        $username = $this->request->post("username");
        $phone = $this->request->post("phone");
        $phone_model = $this->request->post("phone_model");
        $pay_money = $this->request->post("pay_money");
//        $pay_time =  $this->request->post("pay_time");
//        $pay_type =  $this->request->post("pay_type");
//        $remark =  $this->request->post("remark");
        $num = $this->request->post("num");
        $type = $this->request->post("type"); // 1=转中军值，2=转股票权益


        if (empty($phone) || empty($username)) {
            $this->error('姓名或手机号不能为空');
        }


        $ins = db('shopro_order_service')->insert([
            'user_id' => $user_id,
            'username' => $username,
            'phone' => $phone,
            'phone_model' => $phone_model,
            'pay_money' => $pay_money,
            'num' => $num,
            'type' => $type,
            'addtime' => date('Y-m-d H:i:s', time())
        ]);
        if ($ins) {
//            if ($type == 1) {
//                // 转中军值
//                $score = [];
//                $score['user_id'] = $user_id;
//                $score['score'] = $pay_money;
//                $score['before'] = db('share_user')->where('user_id', $user_id)->value('score');
//                $score['after'] = $score['before'] + $pay_money;
//                $score['memo'] = '增加';
//                $score['createtime'] = time();
//                $score['type'] = 1;
//                db('user_score_log')->insert($score);
//                db('share_user')->where('user_id', $user_id)->setInc('score', $pay_money);
//            }
//            if ($type == 2) {
//                // 转股票权益
//                $score = [];
//                $score['user_id'] = $user_id;
//                $score['score'] = $pay_money;
//                $score['stock_v'] = $pay_money;
//                $score['mobile'] = $phone;
//                $score['createtime'] = time();
//                $score['type'] = 1;
//                db('score_stock')->insert($score);
//                db('share_user')->where('user_id', $user_id)->setInc('stock', $pay_money);
//
//            }
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }

    /**
     * 未发放津贴岗位
     */
    public function order_jintie()
    {
        $user_id = $this->user_id;
        $username = $this->request->post("username");
        $phone = $this->request->post("phone");
        $level = $this->request->post("level");
        $pay_money = $this->request->post("pay_money");
        $hour = $this->request->post("hour");
        $type = $this->request->post("type"); // 1=转中军值，2=转股票权益

        if (empty($phone) || empty($username)) {
            $this->error('姓名或手机号不能为空');
        }


        $ins = db('shopro_order_jintie')->insert([
            'user_id' => $user_id,
            'username' => $username,
            'phone' => $phone,
            'level' => $level,
            'pay_money' => $pay_money,
            'hour' => $hour,
            'type' => $type,
            'addtime' => date('Y-m-d H:i:s', time())
        ]);
        if ($ins) {
//            if ($type == 1) {
//                // 转中军值
//                $score = [];
//                $score['user_id'] = $user_id;
//                $score['score'] = $pay_money;
//                $score['before'] = db('share_user')->where('user_id', $user_id)->value('score');
//                $score['after'] = $score['before'] + $pay_money;
//                $score['memo'] = '增加';
//                $score['createtime'] = time();
//                $score['type'] = 1;
//                db('user_score_log')->insert($score);
//                db('share_user')->where('user_id', $user_id)->setInc('score', $pay_money);
//            }
//            if ($type == 2) {
//                // 转股票权益
//                $score = [];
//                $score['user_id'] = $user_id;
//                $score['score'] = $pay_money;
//                $score['stock_v'] = $pay_money;
//                $score['mobile'] = $phone;
//                $score['createtime'] = time();
//                $score['type'] = 1;
//                db('score_stock')->insert($score);
//                db('share_user')->where('user_id', $user_id)->setInc('stock', $pay_money);
//
//            }
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }


    /**
     * 手机型号列表
     */
    public function goods_title()
    {
        $list = db('shopro_goods')->field('id,title')->where('type', 'normal')->where('category_ids', 2)->select();
        $this->success('ok', $list);
    }

    /**
     * 获取团队津贴
     * @return void
     */
    public function get_teams_fee()
    {
        //type : 5=品牌专区 2=易购臻品 1=每月一品
        $type = input('type', 5);

        //鉴权 是否为app负责人
        $user = $this->auth->getUser();
        $share_data = db('share_user')->where('user_id', $user['id'])->find();
        if (!$user || $share_data['is_leader'] != 1) {
            //  $this->error(__('无权限查看'));
        }
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);
        $bill_data = (new OrderBill())->OrderBillData($type,$app_id['id']);

        $ladgerProportion1min = (new OrderBill())->ladgerProportionMin($type,1,$app_id['id']);
        $ladgerProportion1max = (new OrderBill())->ladgerProportionMax($type,1,$app_id['id']);
        $ladgerProportion2min = (new OrderBill())->ladgerProportionMin($type,2,$app_id['id']);
        $ladgerProportion2max = (new OrderBill())->ladgerProportionMax($type,2,$app_id['id']);
        $ladgerProportion3min = (new OrderBill())->ladgerProportionMin($type,3,$app_id['id']);
        $ladgerProportion3max = (new OrderBill())->ladgerProportionMax($type,3,$app_id['id']);

        $list5 = [];
        $list1 = [];
        $list2 = [];
        foreach ($bill_data as $k=>$v){
            if($v["company_type"] == 1){
                if($v['calc_type']) $v['proportion'] = 0;
                if($v['proportion_min'] == $v['proportion_max']){
                    $list_5_5["name"] = $v['name']."(".$v['proportion_min']."%)";
                }else{
                    $list_5_5["name"] = $v['name']."(".$v['proportion_min']."-".$v['proportion_max']."%)";
                }

                $list_5_5["amount"] = Db::name("shopro_order_bill")->where(["ledger_id"=>$v['id']])->whereTime('createtime', 'today')->sum("fz_money");
                $list_5_5["ti_amount"] = Db::name("shopro_order_bill")->where(["ledger_id"=>$v['id']])->where("type","<>",0)->whereTime('createtime', 'today')->sum("fz_money");
                $list_5_5["yu_amount"] = Db::name("shopro_order_bill")->where(["ledger_id"=>$v['id'],"type"=>0])->whereTime('createtime', 'today')->sum("fz_money");
                $list5[] = $list_5_5;
            }elseif($v["company_type"] == 2){
                if($v['calc_type']) $v['proportion'] = 0;
                if($v['proportion_min'] == $v['proportion_max']){
                    $list_1_5["name"] = $v['name']."(".$v['proportion_min']."%)";
                }else{
                    $list_1_5["name"] = $v['name']."(".$v['proportion_min']."-".$v['proportion_max']."%)";
                }

                $list_1_5["amount"] = Db::name("shopro_order_bill")->where(["ledger_id"=>$v['id']])->whereTime('createtime', 'today')->sum("fz_money");
                $list_1_5["ti_amount"] = Db::name("shopro_order_bill")->where(["ledger_id"=>$v['id']])->where("type","<>",0)->whereTime('createtime', 'today')->sum("fz_money");
                $list_1_5["yu_amount"] = Db::name("shopro_order_bill")->where(["ledger_id"=>$v['id'],"type"=>0])->whereTime('createtime', 'today')->sum("fz_money");
                $list1[] = $list_1_5;
            }elseif($v["company_type"] == 3){
                if($v['calc_type']) $v['proportion'] = 0;

                if($v['proportion_min'] == $v['proportion_max']){
                    $list_2_5["name"] = $v['name']."(".$v['proportion_min']."%)";
                }else{
                    $list_2_5["name"] = $v['name']."(".$v['proportion_min']."-".$v['proportion_max']."%)";
                }

                $list_2_5["amount"] = Db::name("shopro_order_bill")->where(["ledger_id"=>$v['id']])->whereTime('createtime', 'today')->sum("fz_money");
                $list_2_5["ti_amount"] = Db::name("shopro_order_bill")->where(["ledger_id"=>$v['id']])->where("type","<>",0)->whereTime('createtime', 'today')->sum("fz_money");
                $list_2_5["yu_amount"] = Db::name("shopro_order_bill")->where(["ledger_id"=>$v['id'],"type"=>0])->whereTime('createtime', 'today')->sum("fz_money");
                $list2[] = $list_2_5;
            }

        }
        //type类型下的各级按比例分账结果
        if($ladgerProportion1min == $ladgerProportion1max){
            $ladgerProportion1str = $ladgerProportion1min;
        }else{
            $ladgerProportion1str =  $ladgerProportion1min."-".$ladgerProportion1max;
        }

        if($ladgerProportion2min == $ladgerProportion2max){
            $ladgerProportion2str = $ladgerProportion2min;
        }else{
            $ladgerProportion2str =  $ladgerProportion2min."-".$ladgerProportion2max;
        }

        if($ladgerProportion3min == $ladgerProportion3max){
            $ladgerProportion3str = $ladgerProportion3min;
        }else{
            $ladgerProportion3str =  $ladgerProportion3min."-".$ladgerProportion3max;
        }

            $arr = [
                "name" => "分公司分账：（".$ladgerProportion1str."%）",
                "amount" => Db::name("shopro_order_bill")->where(["fz_type"=>1,'goods_type'=>$type])->whereTime('createtime', 'today')->sum("fz_money"),
                "list" => $list5,
                "name1" => "总公司分账：（".$ladgerProportion2str."%）",
                "amount1" => Db::name("shopro_order_bill")->where(["fz_type"=>2,'goods_type'=>$type])->whereTime('createtime', 'today')->sum("fz_money"),
                "list1" => $list1,
                "name2" => "第三方公司：（".$ladgerProportion3str."%）",
                "amount2" => Db::name("shopro_order_bill")->where(["fz_type"=>3,'goods_type'=>$type])->whereTime('createtime', 'today')->sum("fz_money"),
                "list2" => $list2,

            ];
        $taday_list = Db::name("shopro_order_bill")->whereTime('createtime', 'today')->where('goods_type','in',[1,2,5])->group("order_sn")->select();
        $yesterday_list = Db::name("shopro_order_bill")->whereTime('createtime', 'yesterday')->where('goods_type','in',[1,2,5])->group("order_sn")->select();
        $month_list = Db::name("shopro_order_bill")->whereTime('createtime', 'month')->where('goods_type','in',[1,2,5])->group("order_sn")->select();
        $taday_id_arr = array_column($taday_list, 'id');
        $yesterday_id_arr = array_column($yesterday_list, 'id');
        $month_id_arr = array_column($month_list, 'id');

        $taday = Db::name("shopro_order_bill")->field("sum(total_amount) as total_amount_sum")->where("id","in",$taday_id_arr)->find();
        $yestaday = Db::name("shopro_order_bill")->field("sum(total_amount) as total_amount_sum")->where("id","in",$yesterday_id_arr)->find();
        $month = Db::name("shopro_order_bill")->field("sum(total_amount) as total_amount_sum")->where("id","in",$month_id_arr)->find();

        $type_today_list = Db::name("shopro_order_bill")->where(['goods_type'=>$type])->whereTime('createtime', 'today')->group("order_sn")->select();
        $id_arr = array_column($type_today_list, 'id');
        $type_today = Db::name("shopro_order_bill")->where("id","in",$id_arr)->sum("total_amount");
        $type_today_order = Db::name("shopro_order_bill")->where(['goods_type'=>$type])->whereTime('createtime', 'today')->group("order_sn")->count();

        $tady_sum = Db::name("shopro_order_bill")
            ->whereTime('createtime', 'today')
            ->where(["fz_type"=>1])
            ->where('goods_type','in',[1,2,5])->sum("fz_money");
        $yesterday_sum = Db::name("shopro_order_bill")
            ->whereTime('createtime', 'yesterday')
            ->where(["fz_type"=>1])
            ->where('goods_type','in',[1,2,5])->sum("fz_money");
        $month_sum = Db::name("shopro_order_bill")
            ->whereTime('createtime', 'month')
            ->where(["fz_type"=>1])
            ->where('goods_type','in',[1,2,5])->sum("fz_money");
        $this->success('成功', [
            'month_kpi' => $month['total_amount_sum']??0,
            'yes_kpi' => $yestaday['total_amount_sum']??0,
            'today_kpi' => $taday['total_amount_sum']??0,
            'month_sub_account' => $month_sum??0,
            'yes_sub_account' => $yesterday_sum??0,
            'today_sub_account' => $tady_sum??0,
            'all_account' => $type_today??0,
            'all_order' => $type_today_order??0,
            'sub_list' => $arr,
        ]);

    }

    public function ce()
    {
        $type = input('type', 1);
        //鉴权 是否为app负责人

        $month_kpi = 1000000;
        $yes_kpi = 20000;
        $today_kpi = 20000;
        $month_sub_account = 1000000;
        $yes_sub_account = 20000;
        $today_sub_account = 10000;
        $all_account = 19900;
        $all_order = 1000;
        $arr = [
            0 => [
                'name' => '供应商分账（35%）',
                'amount' => '100000',
                'ti_amount' => '90000',
                'yu_amount' => '10000',
            ],
            1 => [
                'name' => '零批创收分账（23%）',
                'amount' => '100000',
                'ti_amount' => '90000',
                'yu_amount' => '10000',
            ],
            2 => [
                'name' => '总公司综合运营费（1%）',
                'amount' => '100000',
                'ti_amount' => '90000',
                'yu_amount' => '10000',
            ],
            3 => [
                'name' => '总公司平台技术费（2%）',
                'amount' => '100000',
                'ti_amount' => '90000',
                'yu_amount' => '10000',
            ],
            4 => [
                'name' => '广告创收分账（26.1%）',
                'amount' => '100000',
                'ti_amount' => '90000',
                'yu_amount' => '10000',
            ],
            5 => [
                'name' => '分公司联创分账（3%）',
                'amount' => '100000',
                'ti_amount' => '90000',
                'yu_amount' => '10000',
            ],
            6 => [
                'name' => '分公司股东分账（7.9%）',
                'amount' => '100000',
                'ti_amount' => '90000',
                'yu_amount' => '10000',
            ],
            7 => [
                'name' => '分公司团队运营（2%）',
                'amount' => '100000',
                'ti_amount' => '90000',
                'yu_amount' => '10000',
            ],
        ];
        $this->success('成功', [
            'month_kpi' => $month_kpi,
            'yes_kpi' => $yes_kpi,
            'today_kpi' => $today_kpi,
            'month_sub_account' => $month_sub_account,
            'yes_sub_account' => $yes_sub_account,
            'today_sub_account' => $today_sub_account,
            'all_account' => $all_account,
            'all_order' => $all_order,
            'sub_list' => $arr,
        ]);
    }

    const token = '3bc9be795ae6747ac38bdd55da2a927b';

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function tongji_order()
    {
        if (self::token != input('token')) {
            echo "failed";
            return;
        }

        $p = input('p',1);
        switch ($p){
            case 1:
                $project_name = '易购明辰';
                break;
            case 2:
                $project_name = '易购千玺';
                break;
            case 3:
                $project_name = '易购鑫和';
                break;
            case 4:
                $project_name = '易购凯越';
                break;
            case 5:
                $project_name = '易购飞越';
                break;
            case 6:
                $project_name = '易购超凡';
                break;
            case 7:
                $project_name = '易购美汇';
                break;
            case 8:
                $project_name = '中方未来';
                break;
            case 9:
                $project_name = '中盛摩派';
                break;
            case 10:
                $project_name = '中鑫摩派';
                break;
            case 11:
                $project_name = '上品鸿吉';
                break;
            case 12:
                $project_name = '易购光耀';
                break;
            case 13:
                $project_name = '易购宏鸿';
                break;
            case 14:
                $project_name = '易购美商';
                break;
            case 15:
                $project_name = '醒悟';
                break;
            case 16:
                $project_name = '易购新辉';
                break;
            case 17:
                $project_name = '易购臻品';
                break;
            case 18:
                $project_name = '易购宇美';
                break;
            case 19:
                $project_name = '易购德派';
                break;
            case 20:
//                $project_name = '中惠千喜';
                break;
            case 21:
                $project_name = '易购名威';
                break;
            case 22:
                $project_name = '铭德易购';
                break;
            case 23:
                $project_name = '易购云悦';
                break;
            case 24:
                $project_name = '萃品多';
                break;
            case 25:
                $project_name = '易购中壹';
                break;
            case 27:
                $project_name = '易购共生';
                break;
            case 101:
                $project_name = '中派元宇宙';
                break;
            case 102:
                $project_name = '中通摩派';
                break;
            case 28:
                $project_name = '易购星辰';
                break;
        }

        //商品类型 订单数 订单金额  支付方式 团队名称

        //获取所有订单
        $list = \db('shopro_order')->where('status=1')
            ->where('share_retreat=0')
            ->select();

        $arr = $this->sub_order_print($project_name,'品牌专区', 0);
        echo json_encode($arr, JSON_UNESCAPED_UNICODE) . PHP_EOL;

//        $arr = $this->sub_order_print($project_name,'易购臻品', 2);
//        echo json_encode($arr, JSON_UNESCAPED_UNICODE) . PHP_EOL;
//
//        $arr = $this->sub_order_print($project_name,'每月一品', 1);
//        echo json_encode($arr, JSON_UNESCAPED_UNICODE) . PHP_EOL;
//
//        $arr = $this->sub_order_print($project_name,'一起向未来', 3);
//        echo json_encode($arr, JSON_UNESCAPED_UNICODE) . PHP_EOL;
    }

    protected function sub_order_print($project_name, $name, $goods_type)
    {
        $date = strtotime("2022-10-20");
        $where = [];
        if ($goods_type == 0) {
            //品牌专区的
            $pinpai_arr = \db("share_config")->where($where)->field('goods_id')->select();
            $pinpai_ids = array_column($pinpai_arr, 'goods_id');
            $where['goods_id'] = ['in', $pinpai_ids];
            $where['createtime'] = ['in', $pinpai_ids];
        } else {
            $where['one_day'] = $goods_type;
        }

        $sql = "select user_id from shopro_order group by goods_id,user_id having user_id > 3;";
        $list = \db()->query($sql);
        $top_user = array_column($list, 'user_id');

        $users = \db("user")->where('id', 'in', $top_user)->field('nickname,mobile')->select();
        $str = '';
        foreach ($users as $v) {
            $str .= $v['nickname'] . ":" . $v['mobile'] . ";";
        }
        //获取所有订单
        $all_money = \db('shopro_order')
            ->where($where)
            ->where('status=1')
            ->where('share_retreat=0')
            ->sum('pay_fee');

        //获取所有订单数量
        $all_number = \db('shopro_order')
            ->where($where)
            ->where('status=1')
            ->where('share_retreat=0')
            ->count();

        //获取头部订单
        $top_money = \db('shopro_order')
            ->where($where)
            ->where('user_id', 'in', $top_user)
            ->where('status=1')
            ->where('share_retreat=0')
            ->sum('pay_fee');

        //获取头部订单数量
        $top_count = \db('shopro_order')
            ->where($where)
            ->where('status=1')
            ->where('user_id', 'in', $top_user)
            ->where('share_retreat=0')
            ->count();

        //余额支付金额
        $all_amount_pay = \db('shopro_order')
            ->where($where)
            ->where('status=1')
            ->where('platform != "Coupon"')
            ->where('share_retreat=0')
            ->sum('pay_fee');

        //获取余额支付
        $all_amount_count = \db('shopro_order')
            ->where($where)
            ->where('status=1')
            ->where('platform != "Coupon"')
            ->where('share_retreat=0')
            ->count();

        //提货券支付金额
        $all_tihuo_pay = \db('shopro_order')
            ->where($where)
            ->where('status=1')
            ->where('share_retreat=0')
            ->where('platform = "Coupon"')
            ->sum('pay_fee');

        //获取提货券支付
        $all_tihuo_count = \db('shopro_order')
            ->where($where)
            ->where('status=1')
            ->where('share_retreat=0')
            ->where('platform = "Coupon"')
            ->count();

        $exist = \db("order_tongji")
            ->where('project_name', $project_name)
            ->where('name', $name)
            ->find();
        if ($exist) return;

        $arr = [
            'project_name' => $project_name,
            'name' => $name,
            'all_money' => $all_money,
            'all_number' => $all_number,
            'all_amount_pay' => $all_amount_pay,
            'all_amount_count' => $all_amount_count,
            'all_tihuo_pay' => $all_tihuo_pay,
            'all_tihuo_count' => $all_tihuo_count,
            'top_money' => $top_money,
            'top_count' => $top_count,
            'top_user' => $str,
            'addtime' => time(),
        ];
        $config = [
            'type' => 'mysql',
            // 服务器地址
            'hostname' => '127.0.0.1',
            // 数据库名
            'database' => 'sphj_y',
            // 用户名
            'username' => 'sphj_y',
            // 密码
            'password' => 'BirXH8c2HnWcF2Br',
        ];
        Db::connect($config)->name("order_tongji")->insert($arr);

        return [
            '商品类型' => $name,
            '总金额' => $all_money,
            '总订单数' => $all_number,
            '提货券支付金额' => $all_amount_pay,
            '提货券支付订单数' => $all_amount_count,
            '余额支付金额' => $all_tihuo_pay,
            '余额支付订单数' => $all_tihuo_count,
            '头部账号订单数' => $top_money,
            '头部账号支付金额' => $top_count,
        ];
    }
    /**
     * 获取团队津贴
     * @return void
     */
    public function get_teams_fee_1()
    {
        //type : 5=品牌专区 2=易购臻品 1=每月一品
        $type = input('type', 5);

        //鉴权 是否为app负责人
        $user = $this->auth->getUser();
        $share_data = db('share_user')->where('user_id', $user['id'])->find();
        if (!$user || $share_data['is_leader'] != 1) {
            //  $this->error(__('无权限查看'));
        }

        //获取品牌专区，易购臻品，每月一品的商品ID集合。
        //  $goodsid_group1 = Db::table('share_config')->where('type','=',1)->column('goods_id');
       // $goodsid_group = Db::table('shopro_goods')->where('one_day', 'in', [1, 2, 5])->column('id');
        //  $goodsid_group = array_merge($goodsid_group1,$goodsid_group2);

        //每月总业绩
       /* $months_kpi = Db::table('shopro_order')
            ->where('status', '>=', '1')
            ->where('createtime', '>', 1667750400)
            ->where('share_retreat', '=', 0)
            ->where('goods_id', 'in', $goodsid_group)
            ->field("SUM(`goods_amount`) as goods_amount,FROM_UNIXTIME(createtime,'%Y-%m') as months")
            ->group('months')
            ->order('months desc')
            ->select();*/

        //每日总业绩
       /* $days_kpi = Db::table('shopro_order')
            ->where('status', '>=', '1')
            ->where('createtime', '>', 1667750400)
            ->where('share_retreat', '=', 0)
            ->where('goods_id', 'in', $goodsid_group)
            ->field("SUM(`goods_amount`) as goods_amount,FROM_UNIXTIME(createtime,'%Y-%m-%d') as days")
            ->group('days')
            ->order('days desc')
            ->select();*/

        //当月，昨日，当日业绩
       // $month_kpi = isset($months_kpi[0]) ? $months_kpi[0]['goods_amount'] : 0;
       // $yes_kpi = isset($days_kpi[1]) ? $days_kpi[1]['goods_amount'] : 0;
       // $today_kpi = isset($days_kpi[0]) ? $days_kpi[0]['goods_amount'] : 0;

        //type类型下的当日总业绩和订单数
        $fields = [
            'COUNT(1) as order_num',
            'SUM(`goods_amount`) as order_price'
        ];
        if ($type == 5) {
            $config = Db::table('shopro_goods')->where('one_day', '=', 5)->column('id');
            $yu_account = Db::table('shopro_order')->field($fields)->where('goods_id', 'in', $config)->where('status', '>=', 1)->whereTime('createtime', 'today')->where('share_retreat', '=', 0)->where('platform', NULL)->find();
            $coupon_account = Db::table('shopro_order')->field($fields)->where('goods_id', 'in', $config)->where('status', '>=', 1)->whereTime('createtime', 'today')->where('share_retreat', '=', 0)->where('platform', '=', 'Coupon')->find();
        } else {
            if ($type == 2) {
                $goodsid_group3 = Db::table('shopro_goods')->where('one_day', '=', 2)->column('id');
                $yu_account = Db::table('shopro_order')->field($fields)->where('goods_id', 'in', $goodsid_group3)->where('status', '>=', 1)->whereTime('createtime', 'today')->where('share_retreat', '=', 0)->where('platform', NULL)->find();
                $coupon_account = Db::table('shopro_order')->field($fields)->where('goods_id', 'in', $goodsid_group3)->where('status', '>=', 1)->whereTime('createtime', 'today')->where('share_retreat', '=', 0)->where('platform', '=', 'Coupon')->find();
            } else {
                $goodsid_group3 = Db::table('shopro_goods')->where('one_day', '=', 1)->column('id');
                $yu_account = Db::table('shopro_order')->field($fields)->where('goods_id', 'in', $goodsid_group3)->where('status', '>=', 1)->whereTime('createtime', 'today')->where('share_retreat', '=', 0)->where('platform', NULL)->find();
                $coupon_account = Db::table('shopro_order')->field($fields)->where('goods_id', 'in', $goodsid_group3)->where('status', '>=', 1)->whereTime('createtime', 'today')->where('share_retreat', '=', 0)->where('platform', '=', 'Coupon')->find();
            }
        }
        //当月，昨日，当日分账
        $goodsid_group5 = Db::table('shopro_goods')->where('one_day', '=', 5)->column('id');//
        $goodsid_group1 = Db::table('shopro_goods')->where('one_day', '=', 1)->column('id');//每月
        $goodsid_group2 = Db::table('shopro_goods')->where('one_day', '=', 2)->column('id');
        $yu_account5 = Db::table('shopro_order')->field($fields)
            ->where('goods_id', 'in', $goodsid_group5)
            ->where('status', '>=', 1)
            ->whereTime('createtime', 'today')
            ->where('share_retreat', '=', 0)
            ->find();
        $yu_account2 = Db::table('shopro_order')->field($fields)
            ->where('goods_id', 'in', $goodsid_group2)
            ->where('status', '>=', 1)
            ->whereTime('createtime', 'today')
            ->where('share_retreat', '=', 0)
            ->find();
        $yu_account1 = Db::table('shopro_order')->field($fields)
            ->where('goods_id', 'in', $goodsid_group1)
            ->where('status', '>=', 1)
            ->whereTime('createtime', 'today')
            ->where('share_retreat', '=', 0)
            ->find();
        $yes_yu_account5 = Db::table('shopro_order')->field($fields)
            ->where('goods_id', 'in', $goodsid_group5)
            ->where('status', '>=', 1)
            ->whereTime('createtime', 'yesterday')
            ->where('share_retreat', '=', 0)
            ->find();
        $yes_yu_account2 = Db::table('shopro_order')->field($fields)
            ->where('goods_id', 'in', $goodsid_group2)
            ->where('status', '>=', 1)
            ->whereTime('createtime', 'yesterday')
            ->where('share_retreat', '=', 0)
            ->find();
        $yes_yu_account1 = Db::table('shopro_order')->field($fields)
            ->where('goods_id', 'in', $goodsid_group1)
            ->where('status', '>=', 1)
            ->whereTime('createtime', 'yesterday')
            ->where('share_retreat', '=', 0)
            ->find();
        $month_yu_account5 = Db::table('shopro_order')->field($fields)
            ->where('goods_id', 'in', $goodsid_group5)
            ->where('status', '>=', 1)
            ->whereTime('createtime', 'month')
            ->where('share_retreat', '=', 0)
            ->find();
        $month_yu_account2 = Db::table('shopro_order')->field($fields)
            ->where('goods_id', 'in', $goodsid_group2)
            ->where('status', '>=', 1)
            ->whereTime('createtime', 'month')
            ->where('share_retreat', '=', 0)
            ->find();
        $month_yu_account1 = Db::table('shopro_order')->field($fields)
            ->where('goods_id', 'in', $goodsid_group1)
            ->where('status', '>=', 1)
            ->whereTime('createtime', 'month')
            ->where('share_retreat', '=', 0)
            ->find();
        $yes_kpi = round($yes_yu_account5['order_price'] + $yes_yu_account1['order_price'] + $yes_yu_account2['order_price'], 2);
        $today_kpi = round($yu_account5['order_price'] + $yu_account1['order_price'] + $yu_account2['order_price'], 2);
        $month_kpi = round($month_yu_account5['order_price'] + $month_yu_account1['order_price'] + $month_yu_account2['order_price'], 2);

        $today_sub_account = round($yu_account5['order_price'] * 0.329 + $yu_account1['order_price'] * 0.29 + $yu_account2['order_price'] * 0.07, 2);
        $yes_sub_account = round($yes_yu_account5['order_price'] * 0.329 + $yes_yu_account1['order_price'] * 0.29 + $yes_yu_account2['order_price'] * 0.07, 2);
        $month_sub_account = round($month_yu_account5['order_price'] * 0.329 + $month_yu_account1['order_price'] * 0.29 + $month_yu_account2['order_price'] * 0.07, 2);

        //type类型下的当日总业绩和订单数
        $all_account = $yu_account['order_price'] + $coupon_account['order_price'];
        $all_order = $yu_account['order_num'] + $coupon_account['order_num'];

        //分公司
        $fgs = round($all_account * 0.3492, 2);//分公司总金额
        $ti_fgs = round($coupon_account['order_price'] * 0.329, 2);//提货卷金额
        $yu_fgs = round($yu_account['order_price'] * 0.329, 2);//余额金额
        //总公司
        $z_fgs = round($all_account * 0.38, 2);//总公司总金额
        $z_ti_fgs = round($coupon_account['order_price'] * 0.38, 2);//提货卷金额
        $z_yu_fgs = round($yu_account['order_price'] * 0.38, 2);//余额金额
        //第三方
        $d_fgs = round($all_account * 0.2708, 2);//第三方公司总金额
        $d_ti_fgs = round($coupon_account['order_price'] * 0.291, 2);//提货卷金额
        $d_yu_fgs = round($yu_account['order_price'] * 0.291, 2);//余额金额
        //type类型下的各级按比例分账结果
        if ($type == 5) {
            $arr = [
                "name" => "分公司分账：（34.92%）",
                "amount" => $fgs,
                "list" => [
                    0 => [
                        'name' => '零批创收分账（23%）',
                        'amount' => round(($all_account * 0.23), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.23), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.23), 2),
                    ],
                    1 => [
                        'name' => '分公司联创分账（3%）',
                        'amount' => round(($all_account * 0.03), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.03), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.03), 2),
                    ],
                    2 => [
                        'name' => '分公司团队运营（2%）',
                        'amount' => round(($all_account * 0.02), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.02), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.02), 2),
                    ],
                    3 => [
                        'name' => '分公司股东分账（6.92%）',
                        'amount' => round(($all_account * 0.0692), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.0692), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.0692), 2),
                    ],
                ],
                "name1" => "总公司分账：（38%）",
                "amount1" => $z_fgs,
                "list1" => [
                    0 => [
                        'name' => '供应商分账（35%）',
                        'amount' => round(($all_account * 0.35), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.35), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.35), 2),
                    ],
                    1 => [
                        'name' => '总公司平台技术费（2%）',
                        'amount' => round(($all_account * 0.02), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.02), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.02), 2),
                    ],
                    2 => [
                        'name' => '总公司综合运营费（1%）',
                        'amount' => round(($all_account * 0.01), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.01), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.01), 2),
                    ],

                ],
                "name2" => "第三方分账：（27.08%）",
                "amount2" => $d_fgs,
                "list2" => [
                    0 => [
                        'name' => '广告创收分账（26.1%）',
                        'amount' => round(($all_account * 0.261), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.261), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.261), 2),
                    ],
                    1 => [
                        'name' => '支付通道手续费（0.68%）',
                        'amount' => round(($all_account * 0.0068), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.0068), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.0068), 2),
                    ],
                    2 => [
                        'name' => '分账系统通道费（0.3%）',
                        'amount' => round(($all_account * 0.003), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.003), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.003), 2),
                    ],
                ],

            ];

        } elseif ($type == 1) {
            $arr = [
                "name" => "分公司分账：（61.02%）",
                "amount" => round(($all_account * 0.6102), 2),
                "list" => [
                    0 => [
                        'name' => '分公司股东分账（59.02%）',
                        'amount' => round(($all_account * 0.5902), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.5902), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.5902), 2),
                    ],
                    1 => [
                        'name' => '分公司团队运营（2%）',
                        'amount' => round(($all_account * 0.02), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.02), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.02), 2),
                    ],

                ],
                "name1" => "总公司分账：（38%）",
                "amount1" => $z_fgs,
                "list1" => [
                    0 => [
                        'name' => '供应商分账（35%）',
                        'amount' => round(($all_account * 0.35), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.35), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.35), 2),
                    ],
                    1 => [
                        'name' => '总公司平台技术费（2%）',
                        'amount' => round(($all_account * 0.02), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.02), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.02), 2),
                    ],
                    2 => [
                        'name' => '总公司综合运营费（1%）',
                        'amount' => round(($all_account * 0.01), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.01), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.01), 2),
                    ],

                ],
                "name2" => "第三方分账：（0.98%）",
                "amount2" => round(($all_account * 0.0098), 2),
                "list2" => [
                    0 => [
                        'name' => '支付通道手续费（0.68%）',
                        'amount' => round(($all_account * 0.0068), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.0068), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.0068), 2),
                    ],
                    1 => [
                        'name' => '分账系统通道费（0.3%）',
                        'amount' => round(($all_account * 0.003), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.003), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.003), 2),
                    ],
                ],

            ];
        } elseif ($type == 2) {
            $arr = [
                "name" => "分公司分账：（9.02%）",
                "amount" => round(($all_account * 0.0902), 2),
                "list" => [
                    0 => [
                        'name' => '分公司股东分账（7.02%）',
                        'amount' => round(($all_account * 0.0702), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.0702), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.0702), 2),
                    ],
                    1 => [
                        'name' => '分公司团队运营（2%）',
                        'amount' => round(($all_account * 0.02), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.02), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.02), 2),
                    ],

                ],
                "name1" => "总公司分账：（60%）",
                "amount1" => round(($all_account * 0.6), 2),
                "list1" => [
                    0 => [
                        'name' => '易购甄选运营公司（57%）',
                        'amount' => round(($all_account * 0.57), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.57), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.57), 2),
                    ],
                    1 => [
                        'name' => '总公司平台技术费（2%）',
                        'amount' => round(($all_account * 0.02), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.02), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.02), 2),
                    ],
                    2 => [
                        'name' => '总公司综合运营费（1%）',
                        'amount' => round(($all_account * 0.01), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.01), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.01), 2),
                    ],

                ],
                "name2" => "第三方分账：（30.98%）",
                "amount2" => round(($all_account * 0.3098), 2),
                "list2" => [
                    0 => [
                        'name' => '广告创收分账（30%）',
                        'amount' => round(($all_account * 0.3), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.3), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.3), 2),
                    ],
                    1 => [
                        'name' => '支付通道手续费（0.68%）',
                        'amount' => round(($all_account * 0.0068), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.0068), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.0068), 2),
                    ],
                    2 => [
                        'name' => '分账系统通道费（0.3%）',
                        'amount' => round(($all_account * 0.003), 2),
                        'ti_amount' => round(($coupon_account['order_price'] * 0.003), 2),
                        'yu_amount' => round(($yu_account['order_price'] * 0.003), 2),
                    ],
                ],

            ];
        }
        $this->success('成功', [
            'month_kpi' => $month_kpi,
            'yes_kpi' => $yes_kpi,
            'today_kpi' => $today_kpi,
            'month_sub_account' => $month_sub_account,
            'yes_sub_account' => $yes_sub_account,
            'today_sub_account' => $today_sub_account,
            'all_account' => $all_account,
            'all_order' => $all_order,
            'sub_list' => $arr,
        ]);

    }

    /**
     * 快递鸟物流信息查询
     * @return void
     */
    public function kdniao(){
        $CustomerName = $this->request->post("username");//用户名
        $OrderCode = $this->request->post("orderCode");//订单编号
        $ShipperCode = $this->request->post("shipperCode");//快递公司编码
        $LogisticCode = $this->request->post("logisticCode");//快递单号
        // 组装应用级参数
        $requestData= "{".
            "'CustomerName': '$CustomerName',".
            "'OrderCode': '$OrderCode',".
            "'ShipperCode': '$ShipperCode',".
            "'LogisticCode': '$LogisticCode',".
            "}";
        // 组装系统级参数
        $result = array(
            'EBusinessID' => $this->EbusinessID,
            'RequestType' => '8001', //免费即时查询接口指令1002/在途监控即时查询接口指令8001/地图版即时查询接口指令8003
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $result['DataSign'] = $this->encrypt($requestData, $this->ApiKey);
        $this->success('成功', $this->sendPost($this->ReqURL, $result));
    }

    /**
     * 快递鸟查询物流轨迹地图
     * @return mixed
     */
    function kdniaoMap(){
        $OrderCode = $this->request->post("orderCode");//订单编号
        $CustomerName = $this->request->post("username");//用户名
        $ShipperCode = $this->request->post("shipperCode");//快递公司编码
        $LogisticCode = $this->request->post("logisticCode");//快递单号
        $SenderCityName = $this->request->post("senderCityName");//发件人城市
        $ReceiverCityName = $this->request->post("receiverCityName");//收件人城市
//        return $OrderCode .' - '. $CustomerName .' - '. $ShipperCode .' - '. $LogisticCode .' - '. $SenderCityName .' - '. $ReceiverCityName;
        // 组装应用级参数

        $requestData= "{".
            "'OrderCode': '$OrderCode',".
            "'CustomerName': '$CustomerName',".
            "'ShipperCode': '$ShipperCode',".
            "'LogisticCode': '$LogisticCode',".
            "'SenderCityName': '$SenderCityName',".
            "'ReceiverCityName': '$ReceiverCityName',".
            "'IsReturnCoordinates': 1,". //是否返回城市经纬度，1：返回，2：不返回，不填则默认为1
            "'IsReturnRouteMap': 1,". //是否返回轨迹地图，1：返回，2：不返回，不填则默认为2
            "}";
        // 组装系统级参数
        $result = array(
            'EBusinessID' => $this->EbusinessID,
            'RequestType' => '8003',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $result['DataSign'] = $this->encrypt($requestData, $this->ApiKey);
        $this->success('成功', $this->sendPost($this->ReqURL, $result));
    }

    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    public function sendPost($url, $datas) {
        $postdata = http_build_query($datas);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result,true);
    }

    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param ApiKey ApiKey
     * @return DataSign签名
     */
    public function encrypt($data, $ApiKey) {
        return urlencode(base64_encode(md5($data.$ApiKey)));
    }
    public function payPass(){
        //是否开启支付密码
        $is_pay_pass = Db::name("config")->where(['name' => 'is_pay_pass','value'=>2])->find();
        $re_data = [];
        if($is_pay_pass){
            $re_data['is_pay_pass'] = 2;
        }else{
            $re_data['is_pay_pass'] = 1;
        }
        $pay_agreement = Db::name("config")->where(['name' => 'pay_agreement'])->value("value");
        $re_data['pay_agreement'] = $pay_agreement??1;

        $pay_type = Db::name("config")->where(['name'=>'pay_type'])->find();
        if($pay_type && in_array(99,explode(',',$pay_type['value']))){
            $re_data['pay_pri'] = 1;
        }else{
            $re_data['pay_pri'] = 0;
        }
        if($pay_type && in_array(2,explode(',',$pay_type['value']))){
            $re_data['pay_lp'] = 1;
        }else{
            $re_data['pay_lp'] = 0;
        }
        if($pay_type && in_array(3,explode(',',$pay_type['value']))){
            $re_data['pay_ad'] = 1;
        }else{
            $re_data['pay_ad'] = 0;
        }
        if($pay_type && in_array(4,explode(',',$pay_type['value']))){
            $re_data['pay_old'] = 1;
        }else{
            $re_data['pay_old'] = 0;
        }
        if($pay_type && in_array(5,explode(',',$pay_type['value']))){
            $re_data['pay_t'] = 1;
        }else{
            $re_data['pay_t'] = 0;
        }
        if($pay_type && in_array(6,explode(',',$pay_type['value']))){
            $re_data['pay_hzj'] = 1;
        }else{
            $re_data['pay_hzj'] = 0;
        }

        $one_pay = Db::name("config")->where(['name'=>'one_pay'])->find();
        if($one_pay && in_array(99,explode(',',$one_pay['value']))){
            $re_data['one_pri'] = 1;
        }else{
            $re_data['one_pri'] = 0;
        }
        if($one_pay && in_array(2,explode(',',$one_pay['value']))){
            $re_data['one_lp'] = 1;
        }else{
            $re_data['pay_lp'] = 0;
        }
        if($one_pay && in_array(3,explode(',',$one_pay['value']))){
            $re_data['one_ad'] = 1;
        }else{
            $re_data['one_ad'] = 0;
        }
        if($one_pay && in_array(4,explode(',',$one_pay['value']))){
            $re_data['one_old'] = 1;
        }else{
            $re_data['one_old'] = 0;
        }
        if($one_pay && in_array(5,explode(',',$one_pay['value']))){
            $re_data['one_t'] = 1;
        }else{
            $re_data['one_t'] = 0;
        }
        if($one_pay && in_array(6,explode(',',$one_pay['value']))){
            $re_data['one_hzj'] = 1;
        }else{
            $re_data['one_hzj'] = 0;
        }

        $ygzp_pay = Db::name("config")->where(['name'=>'ygzp_pay'])->find();
        if($ygzp_pay && in_array(99,explode(',',$ygzp_pay['value']))){
            $re_data['ygzp_pri'] = 1;
        }else{
            $re_data['ygzp_pri'] = 0;
        }
        if($ygzp_pay && in_array(2,explode(',',$ygzp_pay['value']))){
            $re_data['ygzp_lp'] = 1;
        }else{
            $re_data['ygzp_lp'] = 0;
        }
        if($ygzp_pay && in_array(3,explode(',',$ygzp_pay['value']))){
            $re_data['ygzp_ad'] = 1;
        }else{
            $re_data['ygzp_ad'] = 0;
        }
        if($ygzp_pay && in_array(4,explode(',',$ygzp_pay['value']))){
            $re_data['ygzp_old'] = 1;
        }else{
            $re_data['ygzp_old'] = 0;
        }
        if($ygzp_pay && in_array(5,explode(',',$ygzp_pay['value']))){
            $re_data['ygzp_t'] = 1;
        }else{
            $re_data['ygzp_t'] = 0;
        }
        if($ygzp_pay && in_array(6,explode(',',$ygzp_pay['value']))){
            $re_data['ygzp_hzj'] = 1;
        }else{
            $re_data['ygzp_hzj'] = 0;
        }

        $hycz_pay = Db::name("config")->where(['name'=>'hycz_pay'])->find();
        if($hycz_pay && in_array(99,explode(',',$hycz_pay['value']))){
            $re_data['hycz_pri'] = 1;
        }else{
            $re_data['hycz_pri'] = 0;
        }
        if($hycz_pay && in_array(2,explode(',',$hycz_pay['value']))){
            $re_data['hycz_lp'] = 1;
        }else{
            $re_data['hycz_lp'] = 0;
        }
        if($hycz_pay && in_array(3,explode(',',$hycz_pay['value']))){
            $re_data['hycz_ad'] = 1;
        }else{
            $re_data['hycz_ad'] = 0;
        }
        if($hycz_pay && in_array(4,explode(',',$hycz_pay['value']))){
            $re_data['hycz_old'] = 1;
        }else{
            $re_data['hycz_old'] = 0;
        }
        if($hycz_pay && in_array(5,explode(',',$hycz_pay['value']))){
            $re_data['hycz_t'] = 1;
        }else{
            $re_data['hycz_t'] = 0;
        }
        if($hycz_pay && in_array(6,explode(',',$hycz_pay['value']))){
            $re_data['hycz_hzj'] = 1;
        }else{
            $re_data['hycz_hzj'] = 0;
        }


        $this->success('成功', $re_data);
    }

}
